package com.atguigu.util;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.Constant;
import org.apache.hadoop.hbase.client.Connection;
import redis.clients.jedis.Jedis;

import java.io.IOException;

public class DimUtil {

    public static JSONObject getDimInfo(Connection connection, Jedis jedis, String tableName, String pk) throws IOException {

        //查询Redis数据
        String redisKey = "DIM:" + tableName + ":" + pk;
        String dimInfoStr = jedis.get(redisKey);
        if (dimInfoStr != null) {
            //TTL读更新
            jedis.expire(redisKey, Constant.ONE_DAY);
            return JSONObject.parseObject(dimInfoStr);
        }

        //Redis中没有数据,则查询HBase
        JSONObject dimInfo = HBaseUtil.getData(connection, Constant.HBASE_NAME_SPACE, tableName, pk);

        //将数据存入Redis
        jedis.set(redisKey, dimInfo.toJSONString());
        jedis.expire(redisKey, Constant.ONE_DAY);

        //返回结果
        return dimInfo;
    }

    public static void main(String[] args) throws Exception {

        Connection connection = HBaseUtil.getConnection();
        Jedis jedis = JedisUtil.getJedis();

        long start = System.currentTimeMillis();
        System.out.println(getDimInfo(connection, jedis, "dim_base_trademark", "13"));
        long end1 = System.currentTimeMillis();
        System.out.println(getDimInfo(connection, jedis, "dim_base_trademark", "13"));
        long end2 = System.currentTimeMillis();//0-1

        System.out.println(end1 - start);
        System.out.println(end2 - end1);

        jedis.close();
        connection.close();
    }
}
